package com.ecnu.codelearn.conf;

import com.ecnu.codelearn.common.ApiResult;
import com.ecnu.codelearn.common.RedisKeyPrefix;
import com.ecnu.codelearn.exception.BusinessException;
import com.ecnu.codelearn.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @Author: 曹培胜
 * @Date: 2021/09/05/16:35
 * @Description:
 */
@Service
public class TokenServiceImpl implements TokenService {

    private final RedisUtil redisService;

    public TokenServiceImpl(RedisUtil redisService) {
        this.redisService = redisService;
    }

    /**
     * 创建token
     *
     * @return
     */
    @Override
    public String createToken() {
        String str = UUID.randomUUID().toString().replace("-", "");
        StringBuilder token = new StringBuilder();
        try {
            token.append(RedisKeyPrefix.TOKEN_PREFIX).append(str);
            redisService.setEx(token.toString(), token.toString(), 10000L);
            boolean empty = StringUtils.isEmpty(token.toString());
            if (!empty) {
                return token.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 检验token
     *
     * @param request
     * @return
     */
    @Override
    public boolean checkToken(HttpServletRequest request) throws Exception {
        String token = request.getHeader(RedisKeyPrefix.TOKEN_NAME);
        // header中不存在token
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter(RedisKeyPrefix.TOKEN_NAME);
            // parameter中也不存在token
            if (StringUtils.isEmpty(token)) {
                throw new BusinessException(ApiResult.BAD_ARGUMENT);
            }
        }
        if (!redisService.exists(token)) {
            throw new BusinessException(ApiResult.REPETITIVE_OPERATION);
        }
        boolean remove = redisService.remove(token);

        if (!remove) {
            throw new BusinessException(ApiResult.REPETITIVE_OPERATION);
        }
        return true;
    }

}
